package com.sea.finance.controller;

import com.codecrane.core.controller.UploaderController;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.entity.CreatePlan;
import com.sea.physical.service.CreatePlanService;
import com.sea.product.service.ChannelService;
import com.sea.supply.entity.Bill;
import com.sea.supply.entity.Buy;
import com.sea.supply.service.BillService;
import com.sea.supply.service.BuyService;
import com.sea.supply.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/finance/bill")
public class FinanceBillController {

    @Autowired
    private BuyService buyService;
    @Autowired
    private BillService billService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private CreatePlanService createPlanService;
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));
        return "/sea/finance/bill/main";
    }
    @ResponseBody
    @RequestMapping("/delete")
    public AjaxReturn deleteByIds(@RequestParam("id") Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("操作失败！");
        if (null!=id && billService.delete(id) >0 ) {
            result.setOk(true).setMsg("删除成功");
        }
        return result;
    }


    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        model.addAttribute("bill",billService.findById(id));
        return "/sea/supply/bill/edit";
    }

    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Bill bill) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try{
            if (null != bill && billService.usave(bill) > 0) {
                result.setOk(true).setMsg("修改成功！");
            }
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importClubDo( MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                UploaderController upload=new UploaderController();
                AjaxReturn ajaxReturn = upload.uploadFile(file, null);
                String string = ajaxReturn.getData().toString();
                ajaxReturn.setData(billService.getImgInfo(string));
                return ajaxReturn;
            }
        } catch (RuntimeException e) {
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Bill buy) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        buy.setFlag(1);
        List<Bill> list = billService.findByCnd(buy);
        PageInfo<Bill> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 保存
     * @param bill
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Bill bill) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != bill && billService.save(bill) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前渠道不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 拆分
     * @param buy
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/split", method = RequestMethod.POST)
    public AjaxReturn split(Buy buy) {
        AjaxReturn result = Ajax.fail().setMsg("拆分失败！");
        try{
            if (null != buy && buyService.split(buy) > 0) {
                result.setOk(true).setMsg("拆分成功！");
            }
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, Bill buy) {
        List<Bill> list = billService.findByCnd(buy);
        String[] title = {"供应商","柜号","不含税金额", "税额","含税金额","发票号码","发票代码","状态","备注"};
        String fileName = "发票管理" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "发票管理";
        String[][] content = new String[list.size()][9];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Bill obj = list.get(i);
            content[i][0] = obj.getSupplierName();
            content[i][1] = obj.getCreatePlanNo();
            content[i][2] = obj.getBillPrice() + "";
            content[i][3] = obj.getBillTax() + "";
            content[i][4] = obj.getBillMoney() + "";
            content[i][5] = obj.getBillNumber();
            content[i][6] = obj.getBillCode();
            switch (obj.getBillStatus()) {
                case 0:
                    content[i][7] = "待审核";
                    break;
                case 1:
                    content[i][7] = "审核中";
                    break;
                case 2:
                    content[i][7] = "审核通过";
                    break;
                case 3:
                    content[i][7] = "已拒绝";
                    break;
            }
            content[i][8] = obj.getBillRemark();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
